package cn.gailvlun.gll.widget.edittext;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.MotionEvent;



public class RightImageEditText extends AppCompatEditText {

    private boolean mIsWhenFocusAppear;

    public RightImageEditText(Context context) {
        super(context);

        init();
    }

    public RightImageEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        init();
    }

    public RightImageEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private Drawable rightDrawable;

    protected void init() {
    }

    public void updateRightDrawable(boolean isVisible) {
        setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], isVisible ? rightDrawable : null, getCompoundDrawables()[3]);
    }

    public void setRightDrawable(Drawable drawable, int width, int height) {
        rightDrawable = drawable;
        rightDrawable.setBounds(0, 0, width, height);
    }

    public void setRightDrawable(Drawable drawable) {
        rightDrawable = drawable;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);

        if (mIsWhenFocusAppear) {
            updateRightDrawable(focused && getText().length() > 0);
        }
    }

    public void setWhenFocusAppear(boolean isWhenFocusAppear) {
        mIsWhenFocusAppear = isWhenFocusAppear;

        if (!isWhenFocusAppear) {
            updateRightDrawable(true);
        }
    }

    public boolean isWhenFocusAppear() {
        return mIsWhenFocusAppear;
    }

    public interface OnRightClickListener {
        void onRightClick(RightImageEditText riet);
    }

    protected OnRightClickListener mOnRightClickListener;

    public void setOnRightClickListener(OnRightClickListener onRightClickListener) {
        mOnRightClickListener = onRightClickListener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (getCompoundDrawables()[2] != null) {
                if (event.getX() > (getWidth() - getTotalPaddingRight())
                        && (event.getX() < (getWidth() - getPaddingRight()))) {
                    if (mOnRightClickListener != null) {
                        mOnRightClickListener.onRightClick(this);
                    }
                }
            }
        }
        return super.onTouchEvent(event);
    }
}
